package com.cat.dataStructure;

import java.util.HashMap;
import java.util.PriorityQueue;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/top-k-frequent-elements/?envType=study-plan-v2&envId=top-100-liked
 * @create 2025/9/24 20:38
 * @since JDK17
 */

public class Solution75 {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.merge(num, 1, Integer::sum);
        }
        int[] ans = new int[k];
        PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> b[1] - a[1]);
        for (var kv : map.entrySet()) {
            heap.add(new int[]{kv.getKey(), kv.getValue()});
        }
        for (int i = 0; i < k; i++) {
            ans[i] = heap.poll()[0];
        }

        return ans;
    }
}
